# -*- coding: utf-8 -*-
# @Time    : 2021/6/5 21:41
# @Author  : YIGE
# @Email   : yige@maqu.com
# @File    : tokenMiddleware.py
# @Software: PyCharm
import jwt

from config import token_conf
from utils.resFormatUtil import ResFormat
from yige_shopping import settings


class TokenMiddleware:
    def __init__(self, get_resp):
        self.get_resp = get_resp

    def __call__(self, request):
        # 获取请求信息
        api = f'{request.method}:{request.path}'  # GET:/user/info/

        # 校验是否需要验证
        if api in settings.TOKEN_API:
            # 校验是否有令牌
            authorization = request.META.get('HTTP_AUTHORIZATION')  # 会加上HTTP_前缀，全部大写 拿到Token
            if not authorization or authorization == 'null':
                return ResFormat(status='ACCESS_RESTRICTION').json_response()

            try:
                user = jwt.decode(authorization, token_conf.TOKEN_SECRET_KEY, algorithms=token_conf.ALGORITHMS)
                setattr(request, 'email', user['data'])
            except jwt.exceptions.ExpiredSignatureError:
                return ResFormat(status='OVERDUE_ABNORMAL').json_response()
            except jwt.exceptions.DecodeError:
                return ResFormat(status='PARAM_ERROR').json_response()
            except Exception:
                return ResFormat(status='UNKNOWN_ERROR').json_response()

        # Token通过
        response = self.get_resp(request)
        return response
